/*
 * CRtpPackager.cpp
 *
 *  Created on: 2015年7月5日
 *      Author: terry
 */

#include "CRtpPackager.h"


namespace av
{

CRtpPackager::CRtpPackager():
		m_type(MEDIA_TYPE_NONE)
{
}

CRtpPackager::~CRtpPackager()
{
}

CRtpPackager::CRtpPackager(int type):
	m_type(type)
{
}

void CRtpPackager::slice(const MediaPacket& pkt, int maxSize, RtpPackagerSink* pSink)
{
	if (!pSink)
	{
		return;
	}

	if (pkt.size() <= maxSize)
	{
		RtpPacket pktOut;
		pktOut.data = pkt.data();
		pktOut.size = pkt.size();
		pktOut.ts = (uint32_t)pkt.dts();

		pktOut.mark = true;

		pSink->onSlicePacket(pktOut);
	}
	else
	{
		RtpPacket pktOut;
		pktOut.ts = (uint32_t)pkt.dts();

		uint8_t* p = pkt.data();
		int leftSize = pkt.size();
		while (leftSize > maxSize)
		{
			pktOut.data = p;
			pktOut.size = maxSize;
			pktOut.mark = false;

			p += maxSize;
			leftSize -= maxSize;

			pSink->onSlicePacket(pktOut);
		}

		pktOut.data = p;
		pktOut.size = leftSize;
		pktOut.mark = true;
		pSink->onSlicePacket(pktOut);

	}
}

bool CRtpPackager::join(const RtpPacket& pktIn, MediaPacket& pktOut)
{
	bool found = false;

	comn::ByteBuffer& buffer = m_buffer.getCurBuffer();
	buffer.write(pktIn.data, pktIn.size);

	if (pktIn.mark)
	{
		pktOut.set_type(m_type);
		pktOut.set_dts(pktIn.ts);
		pktOut.set_duration(0);
		pktOut.setData(buffer.data(), buffer.size());

		m_buffer.switchBuffer();
		m_buffer.getCurBuffer().clear();

		found = true;
	}
	return found;
}

void CRtpPackager::reset()
{
    m_buffer.clear();
}




} /* namespace av */
